<template>
<van-icon
        :color="isLiked===1?'#e5645f':'#777'"
        :name="isLiked===1?'good-job':'good-job-o'"
        :loading="loading"
        @click="onLike"
      />
</template>

<script>
import { ref } from 'vue'
import { Toast } from 'vant'
import { addLike, deleteLike } from '@/api/article'
export default {
  name: 'LikeArticle',
  props: {
    isLiked: {
      type: Number, // -1无态度 0不喜欢 1点赞
      required: true
    },
    articleId: {
      type: [Number, String],
      required: true
    }
  },
  setup (props, context) {
    const loading = ref(false)// 是否处于加载状态
    async function onLike () {
      loading.value = true
      try {
        if (props.isLiked === 1) {
          // 取消点赞
          await deleteLike(props.articleId)
          context.emit('deleteLike')
          Toast('已取消')
        } else {
          // 点赞
          await addLike(props.articleId)
          context.emit('addLike')
          Toast('点赞成功')
        }
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast('请先登录')
        } else {
          Toast('操作失败')
        }
      }
      loading.value = false
    }
    return {
      loading,
      onLike
    }
  }
}
</script>

<style>

</style>
